import React, { useState, useEffect } from 'react'
import { Button, Form, Input, Modal, Table, Space, Avatar, Upload, message, Select } from 'antd';
import { PlusOutlined, UploadOutlined } from '@ant-design/icons';
import { getSubscriber, searchSubscriber, editSubscriber, addsubscriber, delSubscriber } from '../../api/subscriber';
import { addManager, getManager, searchManager, delManager, editManager } from '../../api/manager';

const { Option } = Select;

const AddUser = (prop) => {
    const [isModalOpen, setIsModalOpen] = useState(false);
    const [avatarSrc, setAvatarSrc] = useState('')
    const showModal = () => {
        setIsModalOpen(true);
    };
    const props = {
        name: 'file',
        action: 'http://localhost:1234/manager/addmanager/image',
        headers: {
            authorization: 'authorization-text',
        },
        onChange(info) {
            if (info.file.status !== 'uploading') {
                setAvatarSrc(info.file.response)
            }
        },
    };

    const handleCancel = () => {
        setIsModalOpen(false);
    };
    //添加函数
    const onFinish = (values) => {
        console.log(values)
        addManager({ ...values, avatar: avatarSrc })
            .then(res => {
                if (res.status == 200) {
                    message.success("添加成功")
                    setIsModalOpen(false)
                    prop.getInfo()
                }
            })
    };
    return (
        <div>
            <Button onClick={showModal} type="primary" icon={<PlusOutlined />}>
                添加管理员信息
            </Button>
            <Modal
                title="添加管理员信息"
                open={isModalOpen}
                onCancel={handleCancel}
                footer={null}
            >
                <Form
                    name="basic"
                    layout='vertical'
                    style={{
                        maxWidth: 400,
                        margin: '50px auto'
                    }}

                    onFinish={onFinish}

                    autoComplete="off"

                >

                    <Form.Item
                        name="avatar"
                    >
                        {
                            avatarSrc.includes('/') ? <Avatar size='large' src={avatarSrc} /> :
                                <Avatar size={'large'} src={`http://localhost:1234/avatar/image/${avatarSrc}`} />
                        }

                        <Upload {...props}>
                            <Button icon={<UploadOutlined />}>上传图片</Button>
                        </Upload>
                    </Form.Item>
                    <Form.Item
                        label="昵称"
                        name="name"
                    >

                        <Input />
                    </Form.Item>

                    <Form.Item
                        label="密码"
                        name="pwd"
                        rules={[
                            {
                                required: true,
                                message: 'Please input your password!',
                            },
                        ]}
                    >
                        <Input.Password />
                    </Form.Item>
                    <Form.Item
                        name="role"
                        label="管理员权限"
                        rules={[
                            {
                                required: true,
                                message: 'Please input your password!',
                            },
                        ]}
                    >
                        <Select
                            allowClear
                        >
                            <Option value="超级管理员">超级管理员</Option>
                            <Option value="普通管理员">普通管理员</Option>
                        </Select>
                    </Form.Item>
                    <Form.Item
                        noStyle
                        shouldUpdate={(prevValues, currentValues) => prevValues.gender !== currentValues.gender}
                    >
                        {({ getFieldValue }) =>
                            getFieldValue('gender') === 'other' ? (
                                <Form.Item
                                    name="customizeGender"
                                    label="Customize Gender"

                                >
                                    <Input />
                                </Form.Item>
                            ) : null
                        }
                    </Form.Item>
                    <Form.Item>

                        <Button

                            block

                            shape='round'

                            type="primary"

                            htmlType="submit"

                        >

                            确认修改

                        </Button>

                    </Form.Item>

                </Form>

            </Modal>

        </div>

    )

}
const EditUser = (prop) => {
    const [isModalOpen, setIsModalOpen] = useState(false);
    const [avatarSrc, setAvatarSrc] = useState('')
    const [user, setUser] = useState({})
    const showModal = () => {
        console.log(prop)
        setIsModalOpen(true);
        setUser(prop.user)
        setAvatarSrc(prop.user.avatar)
    };

    const props = {
        name: 'file',
        action: 'http://localhost:1234/manager/editmanager/image?id=' + user.id,
        headers: {
            authorization: 'authorization-text',
        },
        onChange(info) {
            console.log(info);
            if (info.file.status !== 'uploading') {
                console.log(info.file.response);
                setUser({ ...user, avatar: info.file.response.avatar })
                setAvatarSrc(info.file.response.avatar)
            }
        },
    };

    const handleCancel = () => {
        setIsModalOpen(false);
    };
    //添加函数
    const onFinish = (values) => {
        editManager({ ...values, avatar: avatarSrc, id: user.id })
            .then(res => {
                if (res.status == 200) {
                    message.success("修改成功")
                    setIsModalOpen(false)
                    prop.getInfo()
                }
            })
    };
    return (
        <div>
            <a onClick={showModal} type="primary" icon={<PlusOutlined />}>
                编辑
            </a>
            <Modal
                title="修改用户信息"
                open={isModalOpen}
                onCancel={handleCancel}
                footer={null}
            >
                <Form
                    name="basic"
                    layout='vertical'
                    style={{
                        maxWidth: 400,
                        margin: '50px auto'
                    }}

                    onFinish={onFinish}

                    autoComplete="off"

                >

                    <Form.Item
                        name="avatar"
                    >
                        {
                            avatarSrc.includes('/') ? <Avatar size='large' src={avatarSrc} /> :
                                <Avatar size={'large'} src={`http://localhost:1234/avatar/image/${avatarSrc}`} />
                        }
                        <Upload {...props}>
                            <Button icon={<UploadOutlined />}>上传图片</Button>
                        </Upload>
                    </Form.Item>
                    <Form.Item
                        label="昵称"
                        name="name"
                        initialValue={user.name}
                    >

                        <Input />
                    </Form.Item>

                    <Form.Item
                        label="密码"
                        name="pwd"
                        initialValue={user.pwd}
                    >
                        <Input.Password />
                    </Form.Item>
                    <Form.Item
                        name="role"
                        label="管理员权限"
                        rules={[
                            {
                                required: true,
                                message: '请选择权限',
                            },
                        ]}
                    >
                        <Select
                            allowClear
                        >
                            <Option value="超级管理员">超级管理员</Option>
                            <Option value="普通管理员">普通管理员</Option>
                        </Select>
                    </Form.Item>
                    <Form.Item
                        noStyle
                        shouldUpdate={(prevValues, currentValues) => prevValues.gender !== currentValues.gender}
                    >
                        {({ getFieldValue }) =>
                            getFieldValue('gender') === 'other' ? (
                                <Form.Item
                                    name="customizeGender"
                                    label="Customize Gender"

                                >
                                    <Input />
                                </Form.Item>
                            ) : null
                        }
                    </Form.Item>
                    <Form.Item>

                        <Button

                            block

                            shape='round'

                            type="primary"

                            htmlType="submit"

                        >

                            确认修改

                        </Button>

                    </Form.Item>

                </Form>


            </Modal>

        </div>

    )

}

const { Search } = Input

const Manager = () => {
    const columns = [
        {
            title: '头像',
            dataIndex: 'avatar',
            render: (_, record) => {
                return (
                    <div>
                        {
                            record.avatar.includes('/') ? <Avatar size='large' src={record.avatar} /> :
                                <Avatar size={'large'} src={`http://localhost:1234/avatar/image/${record.avatar}`} />
                        }
                    </div>
                )
            },
        },
        {
            title: '昵称',
            dataIndex: 'name',
        },
        {
            title: '密码',
            dataIndex: 'pwd',
        },
        {
            title: '管理员权限',
            dataIndex: 'role',
        },

        {
            title: '操作',
            dataIndex: 'operate',
            render: (_, record) => (
                <Space size="middle">
                    <EditUser user={record} getInfo={getInfo} />
                    <a onClick={() => del(record.id)}>删除</a>
                </Space>

            ),

        }

    ];
    const [data, setData] = useState([]);
    const [form] = Form.useForm();
    // 分页
    const [total, setTotal] = useState(0);
    const [currentPage, setCurrentPage] = useState(1);
    const [pageSize, setPageSize] = useState(10);
    const [selectedRowKeys, setSelectedRowKeys] = useState([]);
    const [isShow, setIsShow] = useState(false)
    //分页函数
    const onChange = (page, pageSize) => {
        setCurrentPage(page);
        setPageSize(pageSize);
    };
    const getInfo = () => {
        getManager({ currentPage: currentPage, pageSize: pageSize })
            .then(res => {
                const arr = res.pageList.map((i) => ({ ...i, key: i.id }))
                setData(arr);
                setTotal(res.total);
            })
    }
    useEffect(() => {
        getInfo()
    }, [currentPage, pageSize])
    const onSearch = (value) => {
        searchManager({ searchData: value, currentPage: currentPage })
            .then(res => {
                const arr = res.pageList.map((i) => ({ ...i, key: i.id }))
                setData(arr);
                setTotal(res.total)
            })
    }
    const del = (id) => {
        delManager({ id })
            .then(res => {
                if (res.status == 200) {
                    message.success("删除成功")
                    getInfo()
                }
            })
    }
    const onSelectChange = (newSelectedRowKeys) => {
        setIsShow(true)
        if (newSelectedRowKeys.length <= 0) {
            setIsShow(false)
        }
        //key
        console.log('selectedRowKeys changed: ', newSelectedRowKeys);
        setSelectedRowKeys(newSelectedRowKeys);
    };
    const delItem = () => {
        for (var i = 0; i < selectedRowKeys.length; i++) {
            del(selectedRowKeys[i])
        }
        getInfo()
        setSelectedRowKeys([])
    }
    const rowSelection = {
        selectedRowKeys,
        onChange: onSelectChange,
    };
    const hasSelected = selectedRowKeys.length > 0;
    return (

        <div>

            <div style={{ marginBottom: '15px', float: 'left', width: '50%', height: '60px', }}>

                <AddUser style={{ display: 'inline-block' }} getInfo={getInfo} />

            </div>

            <div style={{ marginBottom: '15px', display: 'inline-block', width: '50%', height: '60px', }}>

                <Search style={{ width: '300px', float: 'right' }} placeholder="input search text" onSearch={onSearch} enterButton />

            </div>
            {
                isShow ? <Button onClick={delItem} type='primary'>批量删除</Button> : <></>
            }
            <div

                style={{

                    marginBottom: 16,

                }}

            >

                <span

                    style={{

                        marginLeft: 8,

                    }}

                >

                    {hasSelected ? `Selected ${selectedRowKeys.length} items` : ''}

                </span>

            </div>

            <Form form={form} component={false}>

                <Table



                    bordered

                    rowClassName="editable-row"

                    rowSelection={rowSelection}

                    columns={columns}

                    dataSource={data}

                    pagination={{

                        current: currentPage,

                        onChange: onChange,

                        defaultCurrent: 1,

                        position: ['bottomCenter'],

                        total: total

                    }}

                />

            </Form>

        </div>

    );

};

export default Manager